/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, { memo, useCallback, useEffect } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity, DeviceEventEmitter, EmitterSubscription } from 'react-native';
import { songs, Track } from '../model';
import { useBreakpointValue } from '@hadss/react_native_adaptive_layout/src/hooks/useBreakpointValue';
import GeometryView from '@hadss/react_native_geometry_transition/src';
import SampleTurboModule from '../../basic/SampleTurboModule';
import musicPlayer from '../../util';

interface CurPlaySongProps {
    song: Track;
    setCurrentSong: (song: Track) => void;
    isPlaying: boolean;
    setIsPlaying: (isPlaying: boolean) => void;
}

const ControlIconsPhone = memo(({ togglePlayPause, isPlaying }: { togglePlayPause: () => void; isPlaying: boolean }) => (
    <View style={{ flexDirection: 'row', alignItems: 'flex-end', marginRight: 16, flex: 1 }}>
        <TouchableOpacity onPress={togglePlayPause}>
            <Image
                source={isPlaying ? require('../../../../asset/play_icon.png') : require('../../../../asset/play_icon.svg')}
                style={{ width: 24, height: 24 }}
            />
        </TouchableOpacity>
        <Image source={require('../../../../asset/play_list_icon.png')} style={{ width: 24, height: 24, marginLeft: 16 }} />
    </View>
));

const ControlIconsFold = memo(({ togglePlayPause, isPlaying, playPrevious, playNext }: any) => (
    <View style={{ flexDirection: 'row', alignItems: 'flex-end', justifyContent: 'space-between', marginRight: 24, width: 212 }}>
        <Image source={require('../../../../asset/play_mode.png')} style={{ width: 24, height: 24 }} />
        <TouchableOpacity onPress={playPrevious}>
            <Image source={require('../../../../asset/control_left.png')} style={{ width: 28, height: 28 }} />
        </TouchableOpacity>
        <TouchableOpacity onPress={togglePlayPause}>
            <Image
                source={isPlaying ? require('../../../../asset/play_icon.png') : require('../../../../asset/play_icon.svg')}
                style={{ width: 28, height: 28 }}
            />
        </TouchableOpacity>
        <TouchableOpacity onPress={playNext}>
            <Image source={require('../../../../asset/control_right.png')} style={{ width: 28, height: 28 }} />
        </TouchableOpacity>
        <Image source={require('../../../../asset/play_list_icon.png')} style={{ width: 24, height: 24 }} />
    </View>
));

const ControlIconsTable = memo(({ togglePlayPause, isPlaying, playPrevious, playNext }: any) => (
    <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
        <View style={{ position: 'absolute', flexDirection: 'row', justifyContent: 'space-between', width: 310, left: -350 }}>
            <Image source={require('../../../../asset/play_mode.png')} style={{ width: 24, height: 24 }} />
            <TouchableOpacity onPress={playPrevious}>
                <Image source={require('../../../../asset/control_left.png')} style={{ width: 28, height: 28 }} />
            </TouchableOpacity>
            <TouchableOpacity onPress={togglePlayPause}>
                <Image
                    source={isPlaying ? require('../../../../asset/play_icon.png') : require('../../../../asset/play_icon.svg')}
                    style={{ width: 28, height: 28 }}
                />
            </TouchableOpacity>
            <TouchableOpacity onPress={playNext}>
                <Image source={require('../../../../asset/control_right.png')} style={{ width: 28, height: 28 }} />
            </TouchableOpacity>
            <Image source={require('../../../../asset/play_list_icon.png')} style={{ width: 24, height: 24 }} />
        </View>
        <View style={{ flex: 1 }} />
        <Image source={require('../../../../asset/love_icon.svg')} style={{ width: 24, height: 24 }} />
    </View>
));

const CurPlaySong: React.FC<CurPlaySongProps> = ({ song, setCurrentSong, isPlaying, setIsPlaying }) => {
    const togglePlayPause = useCallback(() => {
        if (isPlaying) {
            musicPlayer.pause();
            setIsPlaying(false);
        } else {
            musicPlayer.play();
            setIsPlaying(true);
        }
    }, [isPlaying, setIsPlaying]);

    const playPrevious = useCallback(() => {
        musicPlayer.previousTrack();
        const currentSong = musicPlayer.getCurrentTrack();
        if (currentSong) {
            setCurrentSong(currentSong);
            setIsPlaying(true);
        }
    }, [setCurrentSong]);

    const playNext = useCallback(() => {
        musicPlayer.nextTrack();
        const currentSong = musicPlayer.getCurrentTrack();
        if (currentSong) {
            setCurrentSong(currentSong);
            setIsPlaying(true);
        }
    }, [setCurrentSong]);

    useEffect(() => {
        let listener: EmitterSubscription | null = null;
        musicPlayer.setOnTrackChange((currentTrack) => {
            setCurrentSong(currentTrack);
        });
        musicPlayer.setOnStatusChange((isPlaying) => {
            setIsPlaying(isPlaying);
        });

        listener = DeviceEventEmitter.addListener('trackChange', () => {
            setCurrentSong(musicPlayer.getCurrentTrack()!);
        });

        setCurrentSong(musicPlayer.getCurrentTrack()!);
        setIsPlaying(musicPlayer.getCurrentStatus());

        return () => {
            listener = null;
        };
    }, []);

    const controlIcons = useBreakpointValue({
        base: <ControlIconsPhone togglePlayPause={togglePlayPause} isPlaying={isPlaying} />,
        sm: <ControlIconsPhone togglePlayPause={togglePlayPause} isPlaying={isPlaying} />,
        md: <ControlIconsFold togglePlayPause={togglePlayPause} isPlaying={isPlaying} playPrevious={playPrevious} playNext={playNext} />,
        lg: <ControlIconsTable togglePlayPause={togglePlayPause} isPlaying={isPlaying} playPrevious={playPrevious} playNext={playNext} />,
        xl: <ControlIconsTable togglePlayPause={togglePlayPause} isPlaying={isPlaying} playPrevious={playPrevious} playNext={playNext} />,
    });

    const curPlaySongInfo = useBreakpointValue({
        base: 155,
        sm: 155,
        md: 155,
        lg: 384,
        xl: 384,
    });

    const itemLeft = useBreakpointValue({
        base: 0,
        sm: 16,
        md: 24,
    });

    return (
        <GeometryView
            style={styles.container}
            geometryViewID={'test'}
            onGeometryViewClick={() => {
                SampleTurboModule.pushStringToHarmony('pages/MusicPlay', 1);
            }}>
            <Image source={require('../../../../asset/cover.png')} style={[styles.albumCover, { marginLeft: itemLeft }]} />
            <View style={[styles.songInfo, { width: curPlaySongInfo }]}>
                <Text style={styles.songTitle}>{song.title}</Text>
                <Text style={styles.songArtist}>{song.artist}</Text>
            </View>
            <View style={{ flex: 1 }} />
            {controlIcons}
        </GeometryView>
    );
};

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 8,
        height: 48,
    },
    albumCover: {
        width: 32,
        height: 32,
        borderRadius: 4,
    },
    songInfo: {
        flexDirection: 'column',
        justifyContent: 'center',
        left: 8,
    },
    songTitle: {
        fontSize: 14,
        fontWeight: '500',
        lineHeight: 19,
        color: 'rgba(0, 0, 0, 0.9)',
    },
    songArtist: {
        fontSize: 10,
        color: 'rgba(0, 0, 0, 0.4)',
        lineHeight: 13,
    },
});

export default CurPlaySong;
